#include <REGX52.H>

#define KEY_QUEUE_SIZE 4

unsigned char keyQueue[KEY_QUEUE_SIZE];
unsigned char keyWriteIndex, keyReadIndex;

/**
  * @brief   获取是否按下按键
  * @details 
  * @param   
  * @retval  1~4分别代表K1~K4，0表示无按下任何按钮
  */
unsigned char Key() {
	unsigned char key = 0;
	if (keyWriteIndex != keyReadIndex) {
		key = keyQueue[keyReadIndex];
		keyReadIndex = (keyReadIndex + 1) % KEY_QUEUE_SIZE;
	}
	return key;
}

/**
  * @brief   扫描独立按键
  * @details 
  * @param   
  * @retval  
  */
void Key_Scan() {
	static unsigned char lastKeyState, debounceCounter;
	unsigned char currentKeyState;
	if (P3_1 == 0) {
		currentKeyState = 1;
	} else if (P3_0 == 0) {
		currentKeyState = 2;
	} else if (P3_2 == 0) {
		currentKeyState = 3;
	} else if (P3_3 == 0) {
		currentKeyState = 4;
	} else {
		currentKeyState = 0;
	}
	
	if (lastKeyState != 0 && currentKeyState == 0) {
		if (debounceCounter >= 3) {	// 去抖
			if (((keyWriteIndex + 1) % KEY_QUEUE_SIZE) != keyReadIndex) {
				keyQueue[keyWriteIndex] = lastKeyState;
				keyWriteIndex = (keyWriteIndex + 1) % KEY_QUEUE_SIZE;
			}
		}
	}
	
	if (currentKeyState == lastKeyState) {
		debounceCounter++;
	} else {
		debounceCounter = 0;
		lastKeyState = currentKeyState;
	}	
}